$(function () {
    var query = {}, fields = 'id|userName|password|name|gender|phone',
        $search = $('.search'), $searchBar = $('.search-btn');
    var config = {
        coloum_num: 8, //列数目
        query: '/salePersonAccount/query?',//分页查询URL,
    };
    $searchBar.click(function () {
        $(this).button('loading');
        console.log({keyword: $search.val()});
        search({keyword: $search.val()});

    });
    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        query = query_;query.timestamp = Date.now(); 
        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page,query,search)


        });
    }

    function render(list) {
        // $('.table-responsive .table tbody')

        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                // re
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td><a href="./detail.html?id='+item.saleId+'">' + item.saleName + '</a></td> \
                <td class="text-right">' + number_format(item.cashTotal,2) + '</td> \
                <td class="text-right">' + number_format(item.cashReceivedTotal,2) + '</td> \
                <td class="text-right">' + number_format(item.cashCanWithDrawTotal,2) + '</td> \
                <td class="text-right">' + number_format(item.cashWithDrawingTotal,2) + '</td> \
                <td class="text-right">' + number_format(item.cashWillReceiveTotal,2) + '</td> \
                </tr>')
            });
            $('.opt-update').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var item = $(this).data('json');
                fields.split('|').map(function (key) {
                    var $item = $('[name=' + key + ']');
                    if ($item[0].type == 'radio') {
                        $('[name=' + key + '][value=' + item[key] + ']').attr('checked', true)
                    } else {
                        $item.val(item[key]);
                    }
                });
            });
            $('.opt-delete').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');

                var item = $(this).data('json');
                if (confirm('确认删除？')) {
                    $.post(config['delete'], {id: item.id}, function (xhr, data) {
                        $(self).button('reset');
                        $(self).closest('tr').remove()
                    });
                } else {
                    $(self).button('reset');
                }
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    search({},true);

    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });

    $("#user-form").validate({
        submitHandler: function (form_) {
            var form = {};
            fields.split('|').map(function (item) {
                form[item] = form_[item].value
            });
            var url = config.create;
            if (form.id) { // is update?
                url = config.update;
            } else {
                delete form.id;
            }
            $.post(url, form, function (xhr, data) {
                $submit.button('reset');
            });
            return false;
        }
    });
    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});